import traceback

from handlers.lib_handlers import necessary_params_check, list_in_list_to_dict_in_list
from submodules.common.lib.log_ import logger

from lib import http
from tools import mysql_

db_name = "house_information"
table_name = "user"
column_names = ['id', 'user_name', 'password', 'user_type', 'created_at', 'avatar', 'introduction', 'nickname', 'roles',
                'token', "status", "updated_at"]


def generate_token(req):
    pass


ERRNO_PASSWORD_WRONG = 0
ERRNO_INTERNAL_ERROR = 0
ERRMSG_INTERNAL_ERROR = 0
ERRMSG_PASSWORD_WRONG = 0
ERRNO_DB_ERROR = 0
ERRMSG_DB_ERROR = 0
ERRNO_SUCCESS = 0
ERRMSG_SUCCESS = 0


def user_login(req):
    try:
        # 定义必传参数
        npl = ["user_name", "password"]

        # 创建返回对象
        res = http.Response()

        # 参数校验
        if (res_tmp := necessary_params_check(npl, req, res)) == True:
            pass
        else:
            res = res_tmp
            return res.__dict__

        # 查询数据
        body = req.body
        user_name = body["user_name"]
        password = body["password"]
        res_db = mysql_.select(db_name, table_name, conditions=[user_name])

        # 返回结果
        if res_db.stauts != False:
            password_db = res_db.res["password"]
            if password == password_db:
                res.code = ERRNO_SUCCESS
                res.data = {}
                res.data["token"] = generate_token(req)
                res.msg = ERRMSG_SUCCESS
            else:
                res.code = ERRNO_PASSWORD_WRONG
                res.msg = ERRMSG_PASSWORD_WRONG
            return res.__dict__
        else:
            res.code = ERRNO_DB_ERROR
            res.msg = ERRMSG_DB_ERROR
            return res.__dict__

    except Exception as e:
        # 异常处理
        res.code = ERRNO_INTERNAL_ERROR
        res.msg = ERRMSG_INTERNAL_ERROR
        logger.error(res.msg)
        logger.error(traceback.format_exc())
        return res.__dict__


def user_info(req):
    try:
        necessary_param_list = ["token"]
        res = http.Response()
        body = req.body

        # 参数校验
        if (res_tmp := necessary_params_check(necessary_param_list=necessary_param_list, type="body", req=req,
                                              res=res)) == True:
            pass
        else:
            res = res_tmp
            return res.__dict__

        # 拼接sql
        token = body["token"]

        sql = f'''SELECT * FROM {db_name}.{table_name} WHERE token = "{token}" limit 100;'''
        logger.info(sql)

        # 执行sql
        res_sql = mysql_.select(sql)
        if res_sql[0] != False:
            res.code = 20000
            res.msg = "success"
            res.data = list_in_list_to_dict_in_list(res_sql[1], column_names)[0]
            res.data["roles"] = [res.data["roles"]]
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql[1]
            return res.__dict__


    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        logger.error(traceback.format_exc())
        return res.__dict__


def user_logout(req):
    return {
        "code": 20000,
        "data": 'success'
    }


def user_create(req):
    try:
        # necessary_param_list = ["neiborhood_id"]
        res = http.Response()
        body = req.body

        # if (res_tmp := necessary_params_check(necessary_param_list=necessary_param_list, type="body", req=req,
        #                                       res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        key_list, value_list = [], []
        for k, v in body.items():
            key_list.append(k)
            value_list.append(v)
        value_list_with_quotes = ['"' + str(x) + '"' for x in value_list]
        sql = f'''INSERT INTO {db_name}.{table_name} ({",".join(key_list)}) VALUES ({",".join(value_list_with_quotes)});'''
        logger.info(sql)
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        return res.__dict__


def user_update_status(req):
    try:
        # necessary_param_list = ["id", "status"]
        res = http.Response()
        body = req.body

        # 参数校验
        # if (res_tmp := necessary_params_check(necessary_param_list=necessary_param_list, type="body", req=req,
        #                                       res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        # 拼接sql
        id = body["id"]
        status = body["status"]

        optional_sql_str_list = []
        for k, v in body.items():
            if v != "":
                optional_sql_str_list.append(f"{k}='{v}'")
        sql = f'''UPDATE {db_name}.{table_name} SET status = '{status}' where id = '{id}';'''
        logger.info(sql)

        # 执行sql
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        return res.__dict__


def user_modify(req):
    try:
        # optional_param_list = ["id", "pricing_persqm", "address", "agency_name", "alias", "city_id"]
        res = http.Response()
        body = req.body

        # 参数校验
        # if (res_tmp := optional_params_check(optional_param_list=optional_param_list, type="body", req=req,
        #                                      res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        # 拼接sql
        id = body["id"]
        optional_sql_str_list = []
        for k, v in body.items():
            if v != "":
                optional_sql_str_list.append(f"{k}='{v}'")
        sql = f'''UPDATE {db_name}.{table_name} SET {",".join(optional_sql_str_list)} where id = {id};'''
        logger.info(sql)

        # 执行sql
        if (res_sql := mysql_.insert(sql)) == True:
            res.code = 20000
            res.msg = "success"
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        logger.error(traceback.format_exc(e))
        return res.__dict__


def user_list(req):
    '''
    :param req:
    :return:
    {
        "code": 0,
        "data": {
            "items": [{...},{...}]
        },
        "msg": "success",
        "total": 0
    }
    '''
    try:
        # optional_param_list = ["id", "city_id", "neiborhood_id", "alias", "status", "page", "limit"]
        res = http.Response()
        body = req.body

        # 参数校验
        # if (res_tmp := optional_params_check(optional_param_list=optional_param_list, type="body", req=req,
        #                                      res=res)) == True:
        #     pass
        # else:
        #     res = res_tmp
        #     return res.__dict__

        # 拼接sql
        body.__delitem__("page")  # 前端无法去除 暂时保留传参，但不使用
        body.__delitem__("limit")  # 前端无法去除 暂时保留传参，但不使用

        optional_sql_str = "WHERE "
        for k, v in body.items():
            if v != "":
                if k == "alias":
                    optional_sql_str += f"{k} like '%{v}%' and "
                else:
                    optional_sql_str += f"{k}='{v}' and "
        if optional_sql_str == "WHERE ":
            optional_sql_str = ""
        else:
            optional_sql_str = optional_sql_str[:-4]
        sql = f'''SELECT * FROM {db_name}.{table_name} {optional_sql_str}{"WHERE" if optional_sql_str == "" else "and"} status = 0 ORDER BY updated_at DESC;'''
        logger.info(sql)

        # 执行sql
        res_sql = mysql_.select(sql)
        if res_sql[0] != False:
            res.code = 20000
            res.msg = "success"
            res.data = {}
            res.data["items"] = list_in_list_to_dict_in_list(res_sql[1], column_names)
            # 返回值添加city_name
            # for i in range(len(res.data["items"])):
            #     city_name = get_city_name(res.data["items"][i]["city_id"])
            #     res.data["items"][i]["city_name"] = city_name
            res.data["total"] = len(res.data["items"])
            return res.__dict__
        else:
            res.code = 1000
            res.msg = res_sql[1]
            return res.__dict__

    except Exception as e:
        res.code = 1000
        res.msg = e.__repr__()
        logger.error(res.msg)
        logger.error(traceback.format_exc())
        return res.__dict__


if __name__ == "__main__":
    from lib.http import Request


    def test_login():
        req = Request()
        req.body = {
            "user_name": "admin",
            "password": "123456"
        }
        res = user_login(req)
        print(res)


    test_login()
